package com.huoniu.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.huoniu.user.entity.User;
import com.huoniu.user.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @类 名： UserServiceImpl <br/>
 * @描 述： <br/>
 * @日 期： 2020/9/20 9:17<br/>
 * @作 者： 侯建军<br/>
 * @版 本： 1.0.0
 * @since JDK 1.8
 */
@Service
@Slf4j
public class UserServiceImpl implements UserService {

    /**
     * users_1
     *
     * @param id
     * @return
     */
    @Override
    @Cacheable(value = "user", key = "'users_'+#id")
    public User getUser(Long id) {
        User user = new User();
        user.setId(id);
        user.setUsername("admin");
        user.setPassword("123456");
        user.setBirth(new Date());
        log.info("{}", "数据缓存执行成功！");
        return user;
    }

    @Override
//    @Cacheable(value="user", key="'users_'+#id")
    @Cacheable(keyGenerator = "cacheKeyGenerator", value = "user")
    // 比较复杂的查询条件，实际中可能是HashMap之类存在各种参数
    public User getUserByUsername(User user) {
        log.info("{}", "数据缓存执行成功！" + JSON.toJSONString(user));
        return user;
    }

    @Override
    public List<User> getList(String page) {
        // 直接读Redis 目录

        return null;
    }

    @Override
    @CacheEvict(value = "user", key = "'users_'+#id")
    public void remove(Long id) {
        log.info("{}", id);
        log.info("{}", "删除成功");
    }

    @Override
    @CachePut(value = "userCache", key = "'users_'+#id")
    public User update(Long id) {
        User user = new User();
        user.setId(id);
        user.setUsername("admin0");
        user.setPassword("1234560");
        user.setBirth(new Date());
        log.info("{}", "数据缓存更新执行成功！");
        return user;
    }

}
